package com.beikbank.modules.baseuser.controller;

import com.alibaba.fastjson.JSONObject;
import com.beikbank.modules.baseuser.service.baidu.FaceDetectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sea_son
 * @date 2018/6/21 12:06
 * 海客森：www.hikson.com
 * QQ：1099161566@qq.com
 * ttp://localhost:8080/admin/modules/baseuser/admin/baseuser/save.do
 */
@Controller
@RequestMapping(value = "/baseuser")
public class BaiduFaceController {

    @Autowired
    private FaceDetectService faceDetectService;


    /**
     * 人脸检测测试页面
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/test.do")
    public ModelAndView queryVoi() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/artificialIntelligence/faceRecognition/test");
        return modelAndView;
    }

    /**
     * 请求人脸检测
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/save.do")
    @ResponseBody
    public Map<String, Object> queryService(@RequestParam("the_file") MultipartFile file) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            //将数据转为流
            InputStream content = file.getInputStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = content.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            //获得二进制数组
            byte[] in2b = swapStream.toByteArray();
            System.out.println(in2b.length);;
            //调用人脸检测的方法
            Map<String, String>  strmap = faceDetectService.detectby(in2b);
            //将map数据封装json传到前台

            //此处JsonUtil未提供，大家可以找一个转json的方法
            //String strjson = JsonUtil.mapToJson(strmap);
            String strjson = JSONObject.toJSONString(strmap);
            modelMap.put("strjson", strjson);
            modelMap.put("success", true);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("data", e.getMessage());
        }
        return modelMap;
    }


}
